package com.itheima.secutiry;

import com.itheima.pojo.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 模拟从数据库获取用户信息
 * @author: dalao
 * @date: 2020/4/13-20:36
 * @Version: 1.0.0
 */
public class MyUserService implements UserDetailsService {
    private  BCryptPasswordEncoder passwordEncoder;

    public BCryptPasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    //模拟数据库中的用户数据
    public  static Map<String, User> map = new HashMap<>();
    public void initData(){
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    /**
     * @param username:页面输入的用户名
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
//        根据用户名查询用户密码, 所拥有的权限
        User dbUser = map.get(username);
//        判断user是否为空
        if(dbUser==null){
            //框架自己处理
            return null;
        }
//        权限集合
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();

        authorities.add(new SimpleGrantedAuthority("checkitem_index"));
        authorities.add(new SimpleGrantedAuthority("checkitem_del"));
        System.out.println(username.equals("admin"));
        if(username.equals("admin")){
            authorities.add(new SimpleGrantedAuthority("checkitem_add"));
        }
              return  new org.springframework.security.core.userdetails.User(username,dbUser.getPassword(),authorities);

    }
}
